import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common'
import customField from 'share/customField'
import approvingService from 'containers/approve/approving-edit.service'
import 'styles/approve/edit-content.scss'
import { Form, Affix, Button, message } from 'antd';
const FormItem = Form.Item;

class EditContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custFormValues: [],
      isLoading: false //保存的loading
    }
  }

  componentWillMount() {};

  componentWillReceiveProps(nextProps) {
    if (nextProps.isResetData) {
      this.setState({custFormValues: []});
      return;
    }
    if (nextProps.awaitToProcessValues && nextProps.awaitToProcessValues.length) {
      this.setState({custFormValues: JSON.parse(JSON.stringify(nextProps.awaitToProcessValues))});
    }
  };

  handleSave = () => {
    const { entityOID, entityType, approvalOID } = this.props.params;
    let { custFormValues } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        custFormValues.map(item=> {
          Object.keys(values).map(key => {
            if (key === item.formValueOID) {
              item = customField.formatFormValue(item, values[key]);
            }
          })
        });
        let params = {
          entityOID,
          entityType,
          approvalOID,
          customFormValueDTOs: JSON.parse(JSON.stringify(custFormValues))
        };
        let url = params.approvalOID ? 'saveData' : 'editSave';
        !params.approvalOID && (delete params.approvalOID);
        this.setState({isLoading: true});
        approvingService[url](params).then(() => {
          this.setState({isLoading:false});
          message.success(messages('request.key189'/*已保存*/));
          this.props.close(true);
        }).catch(err=>{
          this.setState({isLoading:false});
          message.error(err.response.data.message);
        });
      }
    });
  };

  closeSlide = () => {
    this.props.close();
  };

  getRules = (field) => {
    let maxLength = undefined;
    switch (field.messageKey) {
      case 'remark':
      case 'textArea':
      case 'text_area':
        maxLength = 200;
        break;
      case 'title':
      case 'input':
        maxLength = 250;
        break;
      default :
        maxLength = undefined;
        break;
    }
    let rules = [{
      required: field.required,
      message: messages('common.can.not.be.empty', {name: field.fieldName})
    }];
    maxLength && rules.push({
      max: maxLength,
      message: messages('common.max.characters.length', {max: maxLength})
    });
    (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
      validator: (rule, value, callback) => {
        let emptyItem = '';
        value && value.map(item => {
          if (!item.name) {
            emptyItem = messages('loan-billing.key61')/*姓名*/;
            return
          }
          if (!item.certificateNo) {
            emptyItem = messages('loan-billing.key62')/*证件号*/;
          }
        });
        if (!emptyItem) {
          callback();
          return
        }
        callback(messages('common.can.not.be.empty', {name: emptyItem}))
      }
    });
    return rules;
  };

  render() {
    const { custFormValues, isLoading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    return (
      <div className="approve-edit">
        <Form>
          {custFormValues.map(field => {
            if (field.visableType === 2) {
              let rules = this.getRules(field);
              return (
                <FormItem {...formItemLayout} label={field.fieldName} key={field.formValueOID}>
                  {getFieldDecorator(field.formValueOID, {
                    rules,
                    initialValue: customField.getInitialValue(field)
                  })(
                    customField.renderForm({field})
                  )}
                </FormItem>
              )
            }
          })}
        </Form>
        <Affix className="type-affix" offsetBottom={0}>
          <Button type="primary" loading={isLoading} onClick={this.handleSave}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="type-btn" onClick={this.closeSlide}>{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}
const wrappedEditContent = Form.create()(EditContent);
export default connect(mapStateToProps)(wrappedEditContent)
